package net.hserver.socket.common;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.TimeUnit;

public class HSocketContext {

    public final AsynchronousSocketChannel socketChannel;
    private final Handler handler;
    private final ByteBuffer readData = ByteBuffer.allocate(1024);
    private final ChannelRead channelRead = new ChannelRead();

    public HSocketContext(AsynchronousSocketChannel socketChannel, Handler handler) {
        this.socketChannel = socketChannel;
        this.handler = handler;
        bindReadChannel();
        handler.onConnect(this);
    }

    public Handler getHandler() {
        return handler;
    }

    public void bindReadChannel() {
        this.socketChannel.read(readData, 0L, TimeUnit.MILLISECONDS, this, channelRead);
    }

    public byte[] readData() {
        byte[] array = readData.array();
        readData.flip();
        return array;
    }

    public boolean write(byte[] data) {
        try {
            this.socketChannel.write(ByteBuffer.wrap(data)).get();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
